package cn.imvc.app.controllers;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.puff.cache.redis.Redis;

import cn.imvc.app.components.KdniaoTrackQueryAPI;
import cn.imvc.app.domains.GenerateOrderInfo;
import cn.imvc.app.domains.OrderState;
import cn.imvc.app.entities.Account;
import cn.imvc.app.entities.Address;
import cn.imvc.app.entities.GoodsOrder;
import cn.imvc.app.entities.Member;
import cn.imvc.app.entities.Orders;
import cn.imvc.app.entities.StorageOrder;
import cn.imvc.app.models.AccountModel;
import cn.imvc.app.models.AddressModel;
import cn.imvc.app.models.MemberModel;
import cn.imvc.app.models.OrderModel;
import cn.imvc.core.ICache;
import cn.imvc.ipay.IPayChannel;

@Controller
@RequestMapping("/order")
public class OrderControllerImpl implements OrderController {

	private static final Logger log = Logger.getLogger(OrderControllerImpl.class);

	@Autowired
	private OrderModel orderModel;
	@Autowired
	private MemberModel memberModel;
	@Autowired
	private AddressModel addressModel;
	@Autowired
	private AccountModel accountModel;
	@Autowired
	ICache cache;
	@Autowired
	KdniaoTrackQueryAPI kdniaoTrackQueryAPI;

	/**
	 * 订单结算页
	 * 
	 * @param si
	 * @param model
	 * @return
	 */
	@RequestMapping("/preOrderInfo.html")
	public String toPreOrderInfo(String token, String addressId, String singleBuyFlag, String singleBuyInfo,
			Model model) {
		Member member = memberModel.getLoginMember(token);
		if (member == null) {// 未登录处理
			return "redirect:/member/login.html";
		}
		if ("1".equals(singleBuyFlag)) {// 单个商品购买
			if (singleBuyInfo != null) {// 存放null等同删除。此处判断是为了选地址返回时不要再次设置
				cache.put("cartItemInfo", "singleBuyInfo" + token, singleBuyInfo, 60 * 60 * 3);
			}
		} else if ("2".equals(singleBuyFlag)) {// 若是积分购买
			if (singleBuyInfo != null) {// 存放null等同删除。此处判断是为了选地址返回时不要再次设置
				cache.put("cartItemInfo", "pointBuyInfo" + token, singleBuyInfo, 60 * 60 * 3);
			}
		}
		model.addAttribute("singleBuyFlag", singleBuyFlag);
		model.addAttribute("addressId", addressId);
		return "/order/pre_order_info";
	}

	@RequestMapping("/showPreOrderInfo.html")
	public String showPreOrderInfo(String si, String token, Integer addressId, String singleBuyFlag, Model model) {
		Member member = memberModel.getLoginMember(token);
		if (member == null) {// 未登录处理
			return "redirect:/member/login.html";
		}
		Map<String, Object> result = null;
		if ("1".equals(singleBuyFlag)) {
			String singleBuyInfo = cache.get("cartItemInfo", "singleBuyInfo" + token);
			if (singleBuyInfo == null || "".equals(singleBuyInfo)) {
				throw new RuntimeException("商品信息不能为空！！");
			}
			si = singleBuyInfo;
		} else if ("2".equals(singleBuyFlag)) {
			String singleBuyInfo = cache.get("cartItemInfo", "pointBuyInfo" + token);
			if (singleBuyInfo == null || "".equals(singleBuyInfo)) {
				throw new RuntimeException("商品信息不能为空！！");
			}
			si = singleBuyInfo;
		}
		if ("2".equals(singleBuyFlag)) {
			result = orderModel.pointsBuyPreOrderInfo(member, si, addressId);
		} else {
			result = orderModel.updateCartsAndshowPreOrderInfo(member, si, addressId, "1".equals(singleBuyFlag));
		}
		model.addAllAttributes(result);
		// model.addAttribute("si", si);
		return "/order/content";
	}

	@RequestMapping("/generateOrders.html")
	private String generateOrders(GenerateOrderInfo generateOrderInfo, Model model) {
		String token = generateOrderInfo.getToken();
		Member member = memberModel.getLoginMember(token);
		if (member == null) {
			throw new RuntimeException("账号信息丢失！");
		}
		Map<String, Object> result = orderModel.saveGeneratedOrders(member, generateOrderInfo);
		model.addAllAttributes(result);
		// 删不删影响不大
		cache.remove("cartItemInfo", "singleBuyInfo" + generateOrderInfo.getToken());
		return "/order/pay";
	}

	@RequestMapping("/generateOrdersAjax.json")
	private @ResponseBody Map<String, Object> generateOrdersAjax(GenerateOrderInfo generateOrderInfo,
			String pointBuyFlag, Model model) {
		String token = generateOrderInfo.getToken();
		Member member = memberModel.getLoginMember(token);
		if (member == null) {
			throw new RuntimeException("账号信息丢失！");
		}
		Map<String, Object> result = null;
		if ("1".equals(pointBuyFlag)) {
			result = orderModel.savePointsBuy(member, generateOrderInfo);
		} else {
			result = orderModel.saveGeneratedOrders(member, generateOrderInfo);
		}
		model.addAllAttributes(result);
		// 删不删影响不大
		cache.remove("cartItemInfo", "singleBuyInfo" + generateOrderInfo.getToken());
		return result;
	}

	@RequestMapping("cancelOrder.json")
	@ResponseBody
	public Map<String, Object> cancelOrder(Model model, String token, Integer orderId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			resultMap.put("code", "-1");
			resultMap.put("msg", "未登录");
			return resultMap;
		}

		if (orderId == null) {
			resultMap.put("code", "0");
			resultMap.put("msg", "订单不能为空");
			return resultMap;
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);

		resultMap = orderModel.cancelOrder(member, orderId).toMap();

		return resultMap;
	}

	@RequestMapping("cancelPayOrder.json")
	@ResponseBody
	public Map<String, Object> cancelPayOrder(Model model, String token, Integer orderId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			resultMap.put("code", "-1");
			resultMap.put("msg", "未登录");
			return resultMap;
		}

		if (orderId == null) {
			resultMap.put("code", "0");
			resultMap.put("msg", "订单不能为空");
			return resultMap;
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		try {
			if (Redis.getInstance().setnx("Order" + orderId, "aa") == 1) {
				Redis.getInstance().expire("Order" + orderId, 20);
				resultMap = orderModel.cancelPayOrder(member, orderId).toMap();
				Redis.getInstance().remove("Order" + orderId);
			} else {
				resultMap.put("code", "0");
				resultMap.put("msg", "订单正在被操作");
			}
		} catch (Exception e) {
			Redis.getInstance().remove("Order" + orderId);
			log.error("orderId" + orderId + "     " + e.toString());
			resultMap.put("code", "0");
			resultMap.put("msg", "您的账户异常,不能取消该订单");
		}

		return resultMap;
	}

	@RequestMapping("receiptStorageOrder.json")
	@ResponseBody
	public Map<String, Object> receiptStorageOrder(Model model, String token, Integer storageOrderId, String payPass) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			resultMap.put("code", "-1");
			resultMap.put("msg", "未登录");
			return resultMap;
		}

		if (storageOrderId == null) {
			resultMap.put("code", "0");
			resultMap.put("msg", "订单不能为空");
			return resultMap;
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		Account account = member.getAccount();
		if (account.getPaypwd() == null || "".equals(account.getPaypwd())) {
			resultMap.put("code", "0");
			resultMap.put("msg", "请设置支付密码");
			return resultMap;
		}
		if (!accountModel.checkPayPw(account, payPass)) {
			resultMap.put("code", "0");
			resultMap.put("msg", "支付密码错误");
			return resultMap;
		}

		try {
			resultMap = orderModel.receiptStorageOrder(member, storageOrderId).toMap();
		} catch (Exception e) {
			resultMap.put("code", "0");
			resultMap.put("msg", "您的账户异常,不能取消该订单");
		}

		return resultMap;
	}

	@RequestMapping("/detail.html")
	public String detail(Model model, String token, Integer orderId) {
		Member member = memberModel.getLoginMember(token);
		if (member == null) {// 未登录处理
			return "redirect:/member/login.html";
		}
		Orders order = orderModel.get(orderId);
		if (order == null) {
			return "redirect:/buyer/buyer.html";
		}
		if (order.getMember().getId() != member.getId()) {
			return "redirect:/member/login.html";
		}
		model.addAttribute("order", order);
		model.addAttribute("orderState", OrderState.elMap);
		return "/order/detail";
	}

	@RequestMapping("/detail.htm")
	public String pcdetail(Model model, String token, Integer storageOrderId) {
		Member member = memberModel.getLoginMember(token);
		if (member == null) {// 未登录处理
			return "redirect:/member/login.htm";
		}
		StorageOrder storageOrder = orderModel.getStorageOrder(storageOrderId);
		if (storageOrder == null) {
			return "redirect:/buyer/buyer.htm";
		}
		if (storageOrder.getMember().getId() != member.getId()) {
			return "redirect:/member/login.htm";
		}
		model.addAttribute("storageOrder", storageOrder);
		model.addAttribute("orderState", OrderState.elMap);
		model.addAttribute("payChannel", IPayChannel.elMap);

		return "/order/pcdetail";
	}

	@RequestMapping("getExpress.json")
	@ResponseBody
	public Map<String, Object> getExpress(Model model, String token, Integer storageOrderId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			resultMap.put("code", "-1");
			resultMap.put("msg", "未登录");
			return resultMap;
		}

		if (storageOrderId == null) {
			resultMap.put("code", "0");
			resultMap.put("msg", "订单不能为空");
			return resultMap;
		}
		StorageOrder storageOrder = orderModel.getStorageOrder(storageOrderId);

		if (storageOrder == null) {
			resultMap.put("code", "0");
			resultMap.put("msg", "订单不能为空");
			return resultMap;
		}
		if (storageOrder.getExpressCode() == null) {
			resultMap.put("code", "0");
			resultMap.put("msg", "还没有发送快递");
			return resultMap;
		}
		try {

			// String
			// expressStr=kdniaoTrackQueryAPI.getOrderTracesByJson("YTO","882586230231837517");
			String expressStr = kdniaoTrackQueryAPI.getOrderTracesByJson(storageOrder.getExpress().getCode(),
					storageOrder.getExpressCode());
			resultMap.put("code", "1");
			resultMap.put("msg", expressStr);
		} catch (Exception e1) {
			resultMap.put("code", "0");
			resultMap.put("msg", "获取快递信息出错");
			return resultMap;
		}
		return resultMap;
	}

	@RequestMapping("/express.html")
	public String express(Model model, String token, Integer storageOrderId) {
		Member member = memberModel.getLoginMember(token);
		if (member == null) {// 未登录处理
			return "redirect:/member/login.html";
		}
		StorageOrder storageOrder = orderModel.getStorageOrder(storageOrderId);
		if (storageOrder == null) {
			return "redirect:/buyer/buyer.html";
		}
		if (storageOrder.getMember().getId() != member.getId()) {
			return "redirect:/member/login.html";
		}
		model.addAttribute("storageOrder", storageOrder);
		Set<GoodsOrder> goodsOrderSet = storageOrder.getGoodsOrder();
		for (GoodsOrder goodsOrder : goodsOrderSet) {
			model.addAttribute("img", goodsOrder.getImage());
			break;
		}
		return "/order/express";
	}
	// ----pc-------------

	/**
	 * 订单结算页
	 * 
	 * @param token
	 * @param addressId
	 * @param singleBuyFlag
	 * @param singleBuyInfo
	 * @param model
	 * @return
	 */
	@RequestMapping("/preOrderInfo.htm")
	public String pcToPreOrderInfo(String token, String addressId, String singleBuyFlag, String singleBuyInfo,
			Model model) {

		Member member = memberModel.getLoginMember(token);
		if (member == null) {// 未登录处理
			return "redirect:/member/login.htm";
		}
		if ("1".equals(singleBuyFlag)) {// 单个商品购买
			if (singleBuyInfo != null) {// 存放null等同删除。此处判断是为了选地址返回时不要再次设置
				cache.put("cartItemInfo", "pcSingleBuyInfo" + token, singleBuyInfo, 60 * 60 * 3);
			}
		} else if ("2".equals(singleBuyFlag)) {// 若是积分购买
			if (singleBuyInfo != null) {// 存放null等同删除。此处判断是为了选地址返回时不要再次设置
				cache.put("cartItemInfo", "pcPointBuyInfo" + token, singleBuyInfo, 60 * 60 * 3);
			}
		}
		model.addAttribute("singleBuyFlag", singleBuyFlag);
		model.addAttribute("addressId", addressId);
		return "/order/pcpre_order_info";
	}

	@RequestMapping("/showPreOrderInfo.htm")
	public String pcShowPreOrderInfo(String si, String token, Integer addressId, String singleBuyFlag, Model model) {
		Member member = memberModel.getLoginMember(token);
		if (member == null) {// 未登录处理
			return "redirect:/member/login.htm";
		}
		if ("1".equals(singleBuyFlag)) {
			String singleBuyInfo = cache.get("cartItemInfo", "pcSingleBuyInfo" + token);
			if (singleBuyInfo == null || "".equals(singleBuyInfo)) {
				throw new RuntimeException("商品信息不能为空！！");
			}
			si = singleBuyInfo;
		} else if ("2".equals(singleBuyFlag)) {
			String singleBuyInfo = cache.get("cartItemInfo", "pcPointBuyInfo" + token);
			if (singleBuyInfo == null || "".equals(singleBuyInfo)) {
				throw new RuntimeException("商品信息不能为空！！");
			}
			si = singleBuyInfo;
		}
		Map<String, Object> result = null;
		if ("2".equals(singleBuyFlag)) {
			result = orderModel.pointsBuyPreOrderInfo(member, si, addressId);
		} else {
			result = orderModel.updateCartsAndshowPreOrderInfo(member, si, addressId, "1".equals(singleBuyFlag));
		}
		List<Address> addressList = addressModel.findByMemberId(member.getId());
		model.addAttribute("addressList", addressList);
		model.addAllAttributes(result);
		// model.addAttribute("si", si);
		return "/order/pccontent";
	}

	@RequestMapping("payPage.html")
	public String payPage(Model model, String token, String code) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}
		model.addAttribute("code", code);
		return "order/payPage";
	}

}
